<?php
// wv-3.3 (c) 2008 by Alexander Klein, akx@gmx.net
// Shoutbox
class WV_ShoutBox 
{
	
	private $shoutFilename = '';   // shoutbox data file
	
	// Constructor
	function __construct($filename) 
	{
		// set file name
		$this->shoutFilename = $filename;
	}

	// shoutbox data formatter
	private function formatShoutline ($shoutLine) {
		return '<p><b>' . $shoutLine[1] . '</b> - ' . $shoutLine[0] . ':<br>' . $shoutLine[2] . '</p>';
	}	
	
	// save a shout to the data file
	public function postShout ($shoutText) 
	{
		$shoutFileData = array();
		
		// read csv data file
		$shoutFileHandler = fopen($this->shoutFilename, 'r');
		while ($shoutLine = fgetcsv($shoutFileHandler, 1000, "|")) {
			array_push($shoutFileData, $shoutLine);
		}	
		fclose($shoutFileHandler);
		
		// remove pipe from text and strip HTML tags 
		$shoutText = str_replace('|', '-', $shoutText);
		$shoutText = "\n" . htmlspecialchars(strip_tags($shoutText));	
		
		// add data, time and hostname to data array
		array_push($shoutFileData, array(date('Y-m-d H:i', time()), gethostbyaddr($_SERVER["REMOTE_ADDR"]), $shoutText));		
		
		// write csv data file
		$shoutFileHandler = fopen($this->shoutFilename, 'w');	
		for ($i=0; $i<count($shoutFileData); $i++) {	
			fputcsv($shoutFileHandler, $shoutFileData[$i], '|');
		}
		fclose($shoutFileHandler);
	}

	// load shoutbox HTML
	public function loadShoutbox() 
	{
		$shoutFileData = array();
		
		// load csv data file
		$shoutFileHandler = fopen($this->shoutFilename, 'r');
		while ($shoutLine = fgetcsv($shoutFileHandler, 1000, "|")) {
			array_push($shoutFileData, $this->formatShoutLine($shoutLine));
		}	
		
		// reverse order, newest entries should be on top
		$shoutFileData = array_reverse($shoutFileData);
		
		// print data for Ajax response
		for ($i=0; $i<count($shoutFileData); $i++) {
			echo $shoutFileData[$i];
		}
		fclose($shoutFileHandler);		
	}
	
	
} 
?>